package com.fanjia.taobao.user.controller;

import com.fanjia.taobao.common.util.ResEntity;
import com.fanjia.taobao.common.util.ResponseUtil;
import com.fanjia.taobao.log.aop.Log;
import com.fanjia.taobao.user.entity.User;
import com.fanjia.taobao.user.service.UserRoleService;
import com.fanjia.taobao.user.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fanjia
 * @className UserController
 * @description TODO
 * @date 2021/4/22 9:37
 */
@RestController
@RequestMapping("/userManage")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    UserRoleService userRoleService;




    @PostMapping("/user")
    public ResEntity add(User user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userService.insert(user);
        return ResponseUtil.success("添加用户成功");
    }


    @PutMapping("/user/{id}")
    public ResEntity update(User user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setUpdateTime(LocalDateTime.now());
        userService.update(user);
        return ResponseUtil.success("更新用户成功");
    }


    @DeleteMapping("/user/{id}")
    public ResEntity delete(@PathVariable("id") int id){
         userService.delete(id);
        return ResponseUtil.success("删除用户成功");
    }

    @GetMapping("/user")
    public ResEntity query(User user,@RequestParam(defaultValue = "1") int pageNum,@RequestParam(defaultValue = "10") int pageSize){
        List<User> userList = userService.query(user,pageNum,pageSize);
        int count = userService.queryCount(user);
        Map<String,Object> map = new HashMap<>();
        map.put("userList",userList);
        map.put("count",count);
        return ResponseUtil.success(map);
    }

    /**
     * @author fanjia
     * @description 为用户分配角色
     * @date  2021/4/23 15:57
     **/
    @GetMapping("/userAssignedRoles")
    @Log("为用户分配角色")
    public ResEntity userAssignedRoles(int userId,@RequestParam List<Integer> roleIds){
        userRoleService.userAssignedRoles(userId,roleIds);
        return ResponseUtil.success("用户分配角色成功");
    }




}
